﻿using UnityEngine;
using System.Collections;
using System;
using Newtonsoft.Json;

public class HttpGet : MonoBehaviour
{
    private static HttpGet _instance = null;

    public static HttpGet Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject go = new GameObject();
                go.name = "Http";
                _instance = go.AddComponent<HttpGet>();

            }
            return _instance;
        }
    }
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void Get<T>(string url, Action<T> onSuccess, Action<string> onfail)
    {
        StartCoroutine(RequestGet(url, onSuccess, onfail));
    }

    IEnumerator RequestGet<T>(string url, Action<T> onSuccess, Action<string> onfail)
    {
        WWW www = new WWW(url);
        yield return www;
        if (!string.IsNullOrEmpty(www.text))
        {
            onSuccess(JsonConvert.DeserializeObject<T>(www.text));
        }
        if (!string.IsNullOrEmpty(www.error))
        {
            onfail(www.error);
        }
    }
}
